package com.wutong.teacher_server.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wutong.common_server.result.Response;
import com.wutong.common_server.utils.ResponseUtil;
import com.wutong.teacher_server.entity.Files;
import com.wutong.teacher_server.service.FilesService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author wutong
 * @since 2020-11-05
 */
@RestController
@RequestMapping("/files")
public class FilesController {

    @Autowired
    FilesService filesService;


    @ApiOperation("查询当前用户所有的上传文件")
    @GetMapping("/showUserAllFiles")
    public Response showUserAllFiles(@RequestParam(value = "userId",required = true) Integer userId){

        QueryWrapper<Files> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",userId);
        List<Files> list = filesService.list(queryWrapper);
        return ResponseUtil.success(list);

    }

    @PostMapping("/upload")
    @ApiOperation("单个文件上传")
    public Response upload(@RequestParam("file") MultipartFile file, @RequestParam("userId") Integer userId) throws IOException {
        if (file.isEmpty()) {
            return  ResponseUtil.success("上传失败，请选择文件");
        }
        //获取原始文件名
        String oldFileName = file.getOriginalFilename();
        //获取最后一个.的位置
        int lastIndexOf = oldFileName.lastIndexOf(".");
        //获取文件的后缀名
        String suffix = oldFileName.substring(lastIndexOf);
        //生成新的文件名
        String newFileName = new SimpleDateFormat("yyyyMMddHHmmss") + UUID.randomUUID().toString().replace("-","") + suffix;
        //文件大小
        Long size = file.getSize();
        //文件类型
        String type = file.getContentType();
        //根据日期生成目录
        String realPath = ResourceUtils.getURL("classpath:").getPath() + "/static/files";
        String dateDirPath = realPath + new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        File dateDir = new File(dateDirPath);
        //不存在则创建目录
        if(!dateDir.exists()){
            dateDir.mkdirs();
        }
        //处理文件上传
        file.transferTo(new File(dateDir,newFileName));
        Files files = new Files();
        files.setOldFileName(oldFileName).setNewFileName(newFileName).setFileSize(String.valueOf(size)).setFileType(type).setFilePath(realPath).setUserId(userId);
        boolean b = filesService.saveFiles(files);
        if(b){
            return ResponseUtil.success("上传成功！");
        }
        return ResponseUtil.failure();

    }

    @PostMapping("/uploadMulti")
    @ApiOperation("多个文件上传")
    public Response uploadMulti(@RequestParam("files") MultipartFile[] files,@RequestParam("userId") Integer userId)throws IOException{
        //根据日期生成目录
        String realPath = ResourceUtils.getURL("classpath:").getPath() + "/static/files";
        String dateDirPath = realPath + new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        File dateDir = new File(dateDirPath);
        //不存在则创建目录
        if(!dateDir.exists()){
            dateDir.mkdirs();
        }
        if (files.length <= 0) {
            return  ResponseUtil.success("上传失败，请选择文件");
        }

        for (MultipartFile file : files) {
            //获取原始文件名
            String oldFileName = file.getOriginalFilename();
            //获取最后一个.的位置
            int lastIndexOf = oldFileName.lastIndexOf(".");
            //获取文件的后缀名
            String suffix = oldFileName.substring(lastIndexOf);
            //生成新的文件名
            String newFileName = new SimpleDateFormat("yyyyMMddHHmmss") + UUID.randomUUID().toString().replace("-","") + suffix;
            //文件大小
            Long size = file.getSize();
            //文件类型
            String type = file.getContentType();
            //处理文件上传
            file.transferTo(new File(dateDir,newFileName));
            Files fileList = new Files();
            fileList.setOldFileName(oldFileName).setNewFileName(newFileName).setFileSize(String.valueOf(size)).setFileType(type).setFilePath(realPath).setUserId(userId);
            filesService.saveFiles(fileList);
        }
        return ResponseUtil.success("上传成功！");

    }
}

